﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using OpenQuarters.WebQuarters.Core;
using OpenQuarters.WebQuarters.Utils;
using System.Drawing.Imaging;
using System.Web.Mvc;

namespace OpenQuarters.WebQuarters.Modules.ImageTitle
{
    public enum ImageTitleMode
    {
        PageTitle,
        Manual,
        ParentPageTitle
        //ManualByInstance
    }

    public class ImageTitleModule : Module
    {
        public static Dictionary<string, string> Templates
        {
            get
            {
                var d = new Dictionary<string, string>();
                d.Add("", "Default");
                foreach (var dir in new DirectoryInfo(Oracle.Context.Server.MapPath("~/Templates/")).GetDirectories())
                {
                    if (dir.Name.Contains(typeof(ImageTitleModule).FullName))
                    {
                        foreach (var template in dir.GetFiles("*.ascx", SearchOption.TopDirectoryOnly))
                        {
                            d.Add(template.Name.Replace(".ascx", ""), template.Name.Replace(".ascx", ""));
                        }
                    }
                }
                return d;
            }
        }


        private string template = "";

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown, OptionSource = "OpenQuarters.WebQuarters.Modules.ImageTitle.ImageTitleModule.Templates")]
        public string Template
        {
            get { return template; }
            set { template = value; }
        }

        private ImageTitleMode _mode = ImageTitleMode.PageTitle;
        private string _title = "";
        private string _foreColour = "#000";
        private string _backColour = "#fff";
        private bool _transparent = false;
        private string _font = "";
        private int _fontSize = 12;
        private ImageTitleDirection _textDirection = ImageTitleDirection.Normal;
        private bool _bold = false;
        private bool _italic = false;
        private int _width = 0;
        private int _height = 0;
        private string _format = ImageFormat.Gif.ToString();

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown)]
        public ImageTitleMode Mode
        {
            get { return _mode; }
            set { _mode = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string ForeColour
        {
            get { return _foreColour; }
            set { _foreColour = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public string BackColour
        {
            get { return _backColour; }
            set { _backColour = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.CheckBox)]
        public bool Transparent
        {
            get { return _transparent; }
            set { _transparent = value; }
        }

        public static Dictionary<string, string> Fonts
        {
            get
            {
                var d = new Dictionary<string, string>();
                d.Add("", "[Generic Sans Serif]");
                foreach (var dir in new DirectoryInfo(Oracle.Context.Server.MapPath("~/Resources/")).GetDirectories())
                {
                    if (dir.Name.Contains(typeof(ImageTitleModule).FullName))
                    {
                        foreach (var template in dir.GetFiles("*.*", SearchOption.AllDirectories))
                        {
                            if (System.IO.Path.GetExtension(template.Name).ToLower() == ".ttf" || System.IO.Path.GetExtension(template.Name).ToLower() == ".otf")
                                d.Add("~/" + template.FullName.Replace(Oracle.Request.MapPath("~"), "").Replace("\\", "/"), System.IO.Path.GetFileNameWithoutExtension(template.Name));
                        }
                    }
                }
                return d;
            }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown, OptionSource = "OpenQuarters.WebQuarters.Modules.ImageTitle.ImageTitleModule.Fonts")]
        public string Font
        {
            get { return _font; }
            set { _font = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public int FontSize
        {
            get { return _fontSize; }
            set { _fontSize = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown)]
        public ImageTitleDirection TextDirection
        {
            get { return _textDirection; }
            set { _textDirection = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.CheckBox)]
        public bool Bold
        {
            get { return _bold; }
            set { _bold = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.CheckBox)]
        public bool Italic
        {
            get { return _italic; }
            set { _italic = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public int Width
        {
            get { return _width; }
            set { _width = value; }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.TextBox)]
        public int Height
        {
            get { return _height; }
            set { _height = value; }
        }

        public static Dictionary<string, string> ImageFormats
        {
            get
            {
                var d = new Dictionary<string, string>();

                d.Add(ImageFormat.Bmp.ToString(),  "image/bmp");
                d.Add(ImageFormat.Gif.ToString(), "image/gif");
                d.Add(ImageFormat.Icon.ToString(), "image/vnd.microsoft.icon");
                d.Add(ImageFormat.Jpeg.ToString(), "image/Jpeg");
                d.Add(ImageFormat.Png.ToString(), "image/png");
                d.Add(ImageFormat.Tiff.ToString(), "image/tiff");
                d.Add(ImageFormat.Wmf.ToString(), "image/wmf");

                return d;
            }
        }

        [Newtonsoft.Json.JsonProperty]
        [PropertyConfiguration(PropertyType.DropDown, OptionSource = "OpenQuarters.WebQuarters.Modules.ImageTitle.ImageTitleModule.ImageFormats")]
        public string Format
        {
            get { return _format; }
            set { _format = value; }
        }

        public string ImageUrl
        {
            get
            {
                XmlSerializer Serializer = new XmlSerializer(typeof(Core.ImageTitle));
                StringWriter optsStream = new StringWriter();
                Serializer.Serialize(optsStream, this.ToClass());

                string encyptedOptions = Utils.Encryption.RijndaelSimple.Encrypt(optsStream.ToString());

                return string.Format("/CMS/File/ImageTitle/?opts={0}", encyptedOptions);
            }
        }

        public Core.ImageTitle ToClass()
        {
            Core.ImageTitle imageTitle = new OpenQuarters.WebQuarters.Core.ImageTitle();

            switch (this._mode)
            {
                case ImageTitleMode.Manual:
                    if (string.IsNullOrEmpty(_title))
                        imageTitle.title = "Default Title";
                    else
                        imageTitle.title = _title;
                    break;
                case ImageTitleMode.ParentPageTitle:
                    if (CMSPage.Current.CMSPage.ParentPage != null)
                        imageTitle.title = CMSPage.Current.CMSPage.ParentPage.Title;
                    else
                        imageTitle.title = "[Page has no title]";
                    break;
                default:
                    imageTitle.title = CMSPage.Current.Title;
                    break;
            }
            imageTitle.ForeColour = this._foreColour;
            imageTitle.BackColour = this._backColour;
            imageTitle.Transparent = this._transparent;
            imageTitle.Font = this._font;
            imageTitle.FontSize = this._fontSize;
            imageTitle.TextDirection = this._textDirection;
            imageTitle.Bold = this._bold;
            imageTitle.Italic = this._italic;
            imageTitle.Width = this._width;
            imageTitle.Height = this._height;
            imageTitle.Format = this._format.ToString();

            return imageTitle;
        }

        public override void Initialise()
        {
            this.ModuleName = "Image Title Module";
            this.ModuleDescription = "Places a generated Image Title on the page.";
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (string.IsNullOrEmpty(this.template))
            {
                System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
                image.ImageUrl = this.ImageUrl;
                image.AlternateText = this.ToClass().title;
                this.Controls.Add(image);
            }
            else
            {
                var viewPath = "~/Templates/" + this.GetType().FullName + "/" + this.Template + ".ascx";
                //this.Controls.AddLiteral(GeneralUtils.RenderViewToString(
                //        Oracle.CurrentControllerContext,
                //        viewPath,
                //        null,
                //        new ViewDataDictionary(this),
                //        new TempDataDictionary()));
                this.Controls.AddLiteral(GeneralUtils.RenderPartialToString(viewPath, this));
            }
        }
    }

}